<template>
	<view class="index">
		<view v-if="tabberPageLoadFlagShow(0)" :style="{display: currentIndex === 0 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" :style="{height:`calc(100vh - 50px - ${safeBottom}px / 2)`}"
				scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
				<Home ref="home"></Home>
			</scroll-view>
		</view>
		<view v-if="tabberPageLoadFlagShow(1)" :style="{display: currentIndex === 1 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" :style="{height:`calc(100vh - 50px - ${safeBottom}px / 2)`}"
				scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
				<Center ref="center"></Center>
			</scroll-view>
		</view>
		<view v-if="tabberPageLoadFlagShow(4)" :style="{display: currentIndex === 4 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" :style="{height:`calc(100vh - 50px - ${safeBottom}px / 2)`}"
				scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
				<Ai ref="message"></Ai>
			</scroll-view>
		</view>
		<view v-if="tabberPageLoadFlagShow(2)" :style="{display: currentIndex === 2 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" :style="{height:`calc(100vh - 50px - ${safeBottom}px / 2)`}"
				scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
				<Message ref="message"></Message>
			</scroll-view>
		</view>
		<view v-if="tabberPageLoadFlagShow(3)" :style="{display: currentIndex === 3 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" :style="{height:`calc(100vh - 50px - ${safeBottom}px / 2)`}"
				scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
				<mine ref="mine"></mine>
			</scroll-view>
		</view>

		<u-tabbar :value="currentIndex" style="z-index: 9999999 !important;" :fixed="false" activeColor="#51d0d0"
			:midButton="true" inactiveColor="#707070" @change="switchTabbar">
			<!-- 				:class="[ { 'middle-item': index === 2 }]" -->
			<u-tabbar-item v-for="(item,index) in tabbarList" :text="item.title" :name="item.id" :badge="item.badge"
				:icon="currentIndex==item.id ? item.activeIcon : item.inactiveIcon">
			</u-tabbar-item>
		</u-tabbar>

		<!-- 		<view class="tabbar">
			<block v-for="(item, index) in tabbarList" :key="index">
				<view class="tabbar-item" @click="toIndex(index)">
					<image :src="current == index ? item.activeIcon : item.inactiveIcon"></image>
					<text :class="'font-title' + (current == index ? '-active' : '')">{{item.title}}</text>
				</view>
			</block>
			<view class="mid-btn-arc"></view>
			<view class="mid-btn" @click="toIndex(tabbarList.length % 2)">
				<image class="mid-img" src="/static/tabbar-icons/ai-fill.png"></image>
			</view>
		</view> -->


	</view>
</template>

<script>
	import Home from '../Home/Home.vue'
	import Center from '../Center/Center.vue'
	import Message from '../Message/Message.vue'
	import Ai from '../Ai/Ai.vue'
	import mine from '../mine/mine.vue'

	const open = uni.requireNativePlugin("Html5App-openFile");
	import {
		mapState
	} from 'vuex';
	// var jpushModule = uni.requireNativePlugin("JG-JPush");

	export default {
		components: {
			Home,
			Center,
			Message,
			Ai,
			mine,
		},
		data() {
			return {
				current: 0,

				// tabbar当前被选中的序号
				currentIndex: 0, // -- 定义选中的id
				// 自定义底栏对应页面的加载情况
				tabberPageLoadFlag: [],
				safeBottom: 0, // 安全底部

				linkJPushSum: 0,
			}
		},
		computed: {
			// hasMsg() {
			// 	return this.$store.state.systemConfig.msgConfig.hasMsg;
			// },
			msgNum() { // 未读消息数量
				return this.$store.state.systemConfig.msgConfig.msgNum || 0;
			},
			tabbarList() { // 底部tabbar菜单数据
				const baseItems = [{
						title: '首页',
						activeIcon: 'home-fill',
						inactiveIcon: 'home',
						id: 0,
						badge: ''
					},
					{
						title: '模块',
						activeIcon: 'grid-fill',
						inactiveIcon: 'grid',
						id: 1,
						badge: ''
					},
					{
						title: '消息',
						activeIcon: 'chat-fill',
						inactiveIcon: 'chat',
						id: 2,
						badge: this.msgNum
					},
					{
						title: '我的',
						activeIcon: 'account-fill',
						inactiveIcon: 'account',
						id: 3,
						badge: ''
					}
				];
				const dataValue = this.$store.state.UserInfo.Business;
				// 3.0 4.0 奕华
				const openAi = [1030, 10103, 9051].includes(dataValue);

				if (openAi) {


					const aiItem = {
						title: 'Ai',
						activeIcon: '/static/tabbar-icons/ai.png',
						inactiveIcon: '/static/tabbar-icons/ai-fill.png',
						id: 4
					};
					return [...baseItems.slice(0, 2), aiItem, ...baseItems.slice(2)];
				}

				return baseItems;

			}
		},
		watch: {
			// hasMsg(nval) {

			// 	if (nval == true) {
			// 		this.$store.commit('ChangeAndSetStateData', {
			// 			Name1: 'systemConfig.msgConfig.hasMsg',
			// 			data: false
			// 		});

			// 		this.$store.state.systemConfig.msgConfig.activeCtx.show();
			// 	}
			// },
		},
		onShow() {
			plus.screen.lockOrientation('portrait-primary');
			if (this.$refs.mine && this.$refs.mine.onMyShow && this.currentIndex == 3) {
				this.$refs.mine.onMyShow();
			}

		},
		onLoad(options) {
			let that = this;

			const indexID = Number(options.index || 0); // 这里修改为ID
			// 根据底部tabbar菜单列表设置对应页面的加载情况
			// this.tabberPageLoadFlag = this.tabbarList.map((item, tabbar_index) => {
			// 	return indexID === item.id
			// })
			this.tabberPageLoadFlag = this.tabbarList.map((item, tabbar_index) => {
				return {
					id: item.id,
					type: indexID === item.id
				}
			})
			this.switchTabbar(indexID)


			// 连接SignalR
			// that.$store.dispatch('connect', {
			// 	urlBuilder: that.Request.IPAgreement() +
			// 		that.Request.serverIP().replace(/:(.*?)(?=:|$)/g, ':20001') + '/MSGHub'
			// });

			let IP = that.Request.serverIP().split(":")[0]
			that.$store.dispatch('connect', {
				// urlBuilder: 'http://mes.hzyc.org.cn:20001' + '/MSGHub'
				urlBuilder: that.Request.IPAgreement() + IP + ':20001' + '/MSGHub'
			});


			// 获取消息数据
			/* try {
				that.$store.dispatch('GetMessageInfo').then(ret => {
					if (ret.status == 200) {

						let backType = that.$utils.binarySearch(ret.data.ds, uni.getStorageSync('openMsgDate'));
						console.log(backType);

						if (backType) {
							if (that.$store.state.systemConfig.msgConfig.openMsgBtnType == 'true') {
								that.$store.state.systemConfig.msgConfig.activeCtx.show();
							}
							// that.$store.state.systemConfig.msgConfig.activeCtx.hide();
						}
					}
				})
			} catch (e) {
				console.log(e)
				//TODO handle the exception
			} */


		},
		mounted() {
			let that = this;
			// 安装tbs内核
			that.installTbsKernel();


			let sequence = 1;
			if (uni.getSystemInfoSync().platform == "ios") {
				sequence = 2;
			}

			let alias = this.$store.state.UserInfo.Business + '_' + this.$store.state.UserInfo.UserID;

			// 设置别名
			// jpushModule.setAlias({
			// 	'sequence': sequence,
			// 	'alias': alias,
			// });


			// 标签别名事件回调
			// jpushModule.addTagAliasListener(result => {
			// 	// console.log(result);
			// 	let code = result.code;

			// 	if (code != 0) {
			// 		that.linkJPushSum++;
			// 		if (that.linkJPushSum < 10) {
			// 			// 重新设置别名
			// 			jpushModule.setAlias({
			// 				'sequence': sequence,
			// 				'alias': alias,
			// 			});
			// 		} else {
			// 			// 删除别名
			// 			jpushModule.deleteAlias({
			// 				'sequence': sequence
			// 			})

			// 		}
			// 	}
			// 	// let sequence = result.sequence
			// 	// let tags = result.tags
			// 	// let tag = result.tag
			// 	// let tagEnable = result.tagEnable
			// 	// let alias = result.alias
			// })

			// console.log(that.$store.state.systemConfig.msgConfig.openMsgBtnType);
			// console.log(that.$store.state.systemConfig.msgConfig.activeCtx.show);
			// if (that.$store.state.systemConfig.msgConfig.openMsgBtnType == true) {
			// }
			/* this.$store.commit('ChangeAndSetStateData', {
				Name1: 'systemConfig.msgConfig.openMsgBtnType',
				data: true,
				StorageName: 'openMsgBtnType',
				StorageData: true,
			}); */
			that.$nextTick(() => {
				setTimeout(() => {
					if (that.$store.state.systemConfig.msgConfig.openMsgBtnType && !that.$store.state
						.systemConfig.msgConfig.msgBtnIsHide) {
						that.$store.state.systemConfig.msgConfig.activeCtx.show();
					}
				}, 300)
			})


			that.getSafeBottom();

			plus.push.addEventListener('click', function(msg) {
				console.log(msg)
				// plus.push.clear();
				if (that.$store.state.systemConfig.isLogin) {

					// 点击系统通知栏消息
					// 打开消息列表，清除消息
					// 点击消息--存储当前时间，缓存时间前的都属于已读数据
					uni.setStorageSync('openMsgDate', JSON.stringify(new Date()));

					uni.$emit('msgReload', {
						status: 'reload'
					});
					// if (that.$store.state.systemConfig.msgConfig.openMsgBtnType == 'true') {
					// 	that.$store.state.systemConfig.msgConfig.activeCtx.hide();
					// }
					uni.navigateTo({
						url: '/pages/Message/Message?nav=1'
					})
				}




			}, false);
		},
		methods: {
			installTbsKernel() { // 安装内核tbs
				try {
					let HasTbs = open.isLoadTbs();
					if (!HasTbs) {
						// 判断本地是否存在该路径文件
						if (uni.getStorageSync('tbsFile')) {
							uni.getFileInfo({
								filePath: uni.getStorageSync('tbsFile'),
								success: (res) => {
									console.log(res)
								},
								fail: (err) => {
									console.log(err)

									uni.downloadFile({
										url: this.Request.IPAgreement() + this.Request.serverIP() +
											'/download/arm64-v8a.tbs',
										success: (row) => {
											console.log(row);
											if (row.statusCode === 200) {
												let filepath = plus.io.convertLocalFileSystemURL(
													row
													.tempFilePath);
												uni.setStorageSync('tbsFile', filepath);

												// 安装文件浏览内核文件,安卓端需要
												open.installLocalTbs({
													tbsFilePath: filepath,
													isdelete: false //安装好是否要删除该文件
												}, function(e) {
													console.log(JSON.stringify(e))
												});
											}
										}
									});
								},
							})
						} else {

							uni.downloadFile({
								url: this.Request.IPAgreement() + this.Request.serverIP() +
									'/download/arm64-v8a.tbs',
								success: (res) => {
									if (res.statusCode === 200) {
										let filepath = plus.io.convertLocalFileSystemURL(res.tempFilePath);
										uni.setStorageSync('tbsFile', filepath);

										// 安装文件浏览内核文件,安卓端需要
										open.installLocalTbs({
											tbsFilePath: filepath,
											isdelete: false //安装好是否要删除该文件
										}, function(e) {
											console.log(JSON.stringify(e))
										});
									}
								}
							});

						}
					}

				} catch (e) {
					//TODO handle the exception
				}
			},
			toIndex(index) {
				this.current = index
				this.content = this.tabbarList[index].title
			},

			// 切换导航
			switchTabbar(indexID) {

				const handleNavigation = (url, shouldReload = false) => {
					if (shouldReload) {
						uni.$emit('msgReload', {
							status: 'reload'
						});
					}
					console.log(url);
					uni.navigateTo({
						url
					});
				};
				console.log(indexID);
				switch (indexID) {
					case 4: {
						// 处理AI模块逻辑
						this.$store.commit('ChangeAndSetStateData', {
							Name1: 'appConfigInfo.ActiveModule',
							data: null
						});
						uni.removeStorageSync('ActiveModule');
						handleNavigation('/pages/Ai/Ai');
						break;
					}

					case 2: {
						// 处理消息模块逻辑
						uni.setStorageSync('openMsgDate', JSON.stringify(new Date()));

						// 处理消息按钮隐藏逻辑
						const msgConfig = this.$store.state.systemConfig.msgConfig;
						if (msgConfig.msgBtnIsHide === 'true' && msgConfig.activeCtx) {
							msgConfig.activeCtx.hide();
						}

						handleNavigation('/pages/Message/Message?nav=1', true);
						break;
					}

					default: {
						// 默认tab切换逻辑
						this._switchTabbarPage(indexID);
						break;
					}
				}
			},

			// 导航页面滚动到底部
			tabbarPageScrollLower(e) {},

			// 切换导航页面
			_switchTabbarPage(indexID) {
				// 查找目标标签页配置
				const targetPage = this.tabberPageLoadFlag.find(item => item.id === indexID);

				// 无效标签页直接返回
				if (!targetPage) return;

				// 处理未初始化状态
				if (targetPage.type === undefined) return;

				// 需要激活时执行状态更新
				if (!targetPage.type) {
					this.updateTabLoadStatus(indexID);
				}

				// 更新当前激活索引
				this.currentIndex = indexID;
			},

			// 优化后的状态更新方法（移除冗余参数返回）
			updateTabLoadStatus(id) {
				const index = this.tabberPageLoadFlag.findIndex(item => item.id === id);
				if (index !== -1) {
					// 直接修改原数组引用（Vue的响应式系统会自动检测）
					this.$set(this.tabberPageLoadFlag, index, {
						...this.tabberPageLoadFlag[index],
						type: true
					});
				}
			},
			tabberPageLoadFlagShow(id) {
				let findData = this.tabberPageLoadFlag.find(item => item.id == id);
				return findData ? findData['type'] : false;
			},

			// 获取安全底部高度
			getSafeBottom() {
				let that = this;
				let safeareaBottom = uni.getStorageSync('safeareaBottom');
				if (safeareaBottom) {
					that.safeBottom = safeareaBottom;
				} else {
					uni.getSystemInfo({
						success: function(res) {
							if (res.safeAreaInsets.bottom) {
								that.safeBottom = res.safeAreaInsets.bottom;
								uni.setStorageSync('safeareaBottom', that.safeBottom)
							}
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.index {
		overflow: hidden;
		height: 100vh;
	}



	// .custom-tabbar-page {
	// height: calc(100vh - (50px + env(safe-area-inset-bottom) / 2));
	// }


	::v-deep .middle-item .u-tabbar-item__icon {
		background: red;
		bottom: 20rpx;

		// border-radius: 20rpx;
		.u-icon--right {

			background-color: yellow;
			transform: scale(2);
			border-radius: 20rpx;
		}
	}
</style>